package com.it.tydic.estate.module.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.it.tydic.estate.common.aop.CodeMsg;
import com.it.tydic.estate.common.aop.Result;
import com.it.tydic.estate.common.util.InstaIdGenerator;
import com.it.tydic.estate.common.util.StringUtils;
import com.it.tydic.estate.common.util.TimeUtil;
import com.it.tydic.estate.common.util.ZfbjFinalUtil;
import com.it.tydic.estate.module.mapper.inner.TbCkglGysMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglWpdaMapper;
import com.it.tydic.estate.module.mapper.inner.TbCkglWplbMapper;
import com.it.tydic.estate.module.model.inner.*;
import com.it.tydic.estate.module.service.GysService;
import com.it.tydic.estate.module.service.WplbService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class WplbServiceImpl implements WplbService {

    @Autowired
    private TbCkglWplbMapper wplbMapper;
    @Autowired
    private TbCkglWpdaMapper wpdaMapper;
    /**
     * 新增修改
     * @param wplb
     * @return
     */
    @Override
    public Result insertOrUpdate(TbCkglWplb wplb) {
        //必传项参数校验
        if(StringUtil.isEmpty(wplb.getWplbdm()) || StringUtil.isEmpty(wplb.getWplbmc()) || StringUtil.isEmpty(wplb.getUserId())){
            return  Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        if(StringUtil.isEmpty(wplb.getId())){//判断如果为空新增
            if(checkName(wplb)){
                return  Result.error(CodeMsg.DATA_REPEATE);
            }
            wplb.setZfbj("0");
            wplb.setCreateTime(new Date());
            wplb.setUpdateTime(new Date());
            wplb.setId(String.valueOf(new InstaIdGenerator().nextId(TimeUtil.timeGen())));
            int index = wplbMapper.insert(wplb);
            if(index==0){
                return  Result.error(CodeMsg.INSERT_ERROR);
            }
        }else {//修改
            wplb.setUpdateTime(new Date());
            int index = wplbMapper.updateByPrimaryKeySelective(wplb);
            if(index==0){
                return  Result.error(CodeMsg.UPDATE_ERROR);
            }
        }
        return Result.success(wplb.getId());
    }
    /**
     * 验证物品类别名称是否重复
     * @param wplb
     * @return
     */
    private boolean checkName(TbCkglWplb wplb) {
        boolean flag =false;
        Example example = new Example(TbCkglWplb.class);
        example.createCriteria().andEqualTo("userId", wplb.getUserId()).
                andEqualTo("wplbmc", wplb.getWplbmc()).
                andEqualTo("zfbj", ZfbjFinalUtil.zfbj_zy);
        int num = wplbMapper.selectCountByExample(example);
        if (num > 0)
            flag=true;
        return flag;
    }

    /**
     * 根据主键查询
     * @param id
     * @return
     */
    @Override
    public Result getById(String id) {
        if(StringUtil.isEmpty(id)){
            return Result.error(CodeMsg.EMPTY_PARAM_ERROR);
        }
        TbCkglWplb wplb = wplbMapper.selectByPrimaryKey(id);
        if(wplb==null){
            return Result.error(CodeMsg.DATA_NOT_EXIST);
        }
        return Result.success(wplb);
    }
    /**
     * 列表页面查询
     * @param map
     * @return
     */
    @Override
    public Result pageList(Map<String,Object> map) {
        if(isNotNull(map)){//参数验证
            Map<String,Object> dataMap = new HashMap<>();
            Example example = new Example(TbCkglWplb.class);
            setExample(example,map);//添加查询条件
            PageHelper.startPage((Integer) map.get("pageNum"),(Integer)map.get("pageSize"));
            Page<TbCkglWplb> tbCkglWplbs = (Page<TbCkglWplb>) wplbMapper.selectByExample(example);
            dataMap.put("data",tbCkglWplbs.getResult());
            dataMap.put("totle",tbCkglWplbs.getTotal());
            return Result.success(dataMap);
        }
        return Result.error(CodeMsg.INTER_ERROR);
    }

    private void setExample(Example example, Map<String, Object> map) {
        example.setOrderByClause("UPDATE_TIME DESC");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("zfbj","0").andEqualTo("userId",map.get("userId"));
        if(StringUtils.isNotEmpty(String.valueOf(map.get("wplbdm")))){
            criteria.andLike("wplbdm","%"+String.valueOf(map.get("wplbdm"))+"%");
        }
        if(StringUtils.isNotEmpty(String.valueOf(map.get("wplbmc")))){
            criteria.andLike("wplbmc","%"+String.valueOf(map.get("wplbmc"))+"%");
        }
    }

    /**
     * 根据ids 批量删除
     * @param ids 主键ids数组
     * @return
     */
    @Override
    public Result deleteByIds(List<String> ids) {
        if (ids.size() == 0) {
            return  Result.error(CodeMsg.INTER_ERROR,null);
        }
        Example rkckdmxExample = new Example(TbCkglWpda.class);
        Example.Criteria criteria = rkckdmxExample.createCriteria();
        criteria.andIn("wplb", ids).andEqualTo("zfbj",ZfbjFinalUtil.zfbj_zy);;
        int count=countRoleByExample(rkckdmxExample);
        //判断资源有没有被占用
        if(count>0){
            return Result.error(CodeMsg.RESOURCE_USE);
        }
        TbCkglWplb wplb = new TbCkglWplb();
        wplb.setZfbj("1");
        Example example = new Example(TbCkglWplb.class);
        example.createCriteria().andIn("id",ids);
        int result = wplbMapper.updateByExampleSelective(wplb,example);
        if (result == ids.size()) {
            return  Result.success(CodeMsg.SUCCESS);
        }
        return Result.error(CodeMsg.INTER_ERROR, null);
    }
    public int countRoleByExample(Example example){
        return wpdaMapper.selectCountByExample(example);
    }


    /**
     *验证map参数
     */
    private Boolean isNotNull(Map<String,Object> map) {
        if(StringUtil.isEmpty(String.valueOf(map.get("userId")) ) ||
                StringUtil.isEmpty(String.valueOf(map.get("pageNum")))||
                StringUtil.isEmpty(String.valueOf(map.get("pageSize")))){
            return false;
        }
        return true;
    }

}
